/**
 * 
 */
package com.laozhao.dreamframe.util;

import java.awt.Frame;
import java.util.HashMap;

/**
 * @author laozhao
 * 
 */
public class FrameFactory {

	private static HashMap<String, Object> objMap = new HashMap<String, Object>();
	private static String mainFrameKey;

	@SuppressWarnings("unchecked")
	public static <T> T getInstance(Class<T> clazz) {
		if (objMap.containsKey(clazz.getName())) {
			return (T) objMap.get(clazz.getName());
		} else {
			return createObject(clazz);
		}
	}

	public static Object getInstance(String className) {
		if (objMap.containsKey(className)) {
			return objMap.get(className);
		} else {
			try {
				return createObject(Class.forName(className));
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <X extends Frame> X setMainFrame(Class<X> clazz) {
		if (objMap.containsKey(clazz.getName())) {
			return (X) objMap.get(clazz.getName());
		} else {
			mainFrameKey = clazz.getName();
			return createObject(clazz);
		}
	}

	public static Frame getMainFrame() {
		if (mainFrameKey != null) {
			return (Frame) objMap.get(mainFrameKey);
		} else {
			return null;
		}
	}

	private static synchronized <E> E createObject(Class<E> clazz) {
		if (clazz != null) {
			try {
				E object = clazz.newInstance();
				objMap.put(clazz.getName(), object);
				return object;

			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		} else {
			return null;
		}
		return null;
	}
}
